package com.feeyo.prophet.actions.rcdi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feeyo.prophet.pojo.action.rcdi.FeeyoRcdiReq;
import com.feeyo.prophet.plugins.DbSearchActionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 *  type 是预留字段, 目前对接的是type==1 的 知识问答和法规解读. 后面可能会扩充
 */
@Slf4j
public class FeeyoRcidAction {

    private final String host;
    private final Integer port;

    public FeeyoRcidAction(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    public void run(String id, String input, String lastId, SseEmitter emitter, String chatId) {
        try {
            FeeyoRcdiReq req = JSON.parseObject(input, FeeyoRcdiReq.class);
            String question = req.getQuestion();
            // 先做认证
            String rcdiBefore = DbSearchActionUtils.getRcdiBefore(host, port, question, chatId);
            String rcdiId = getRcdiId(rcdiBefore);
            if (rcdiId != null) {
                DbSearchActionUtils.getRcdiSse(host, port, id, rcdiId, lastId,  emitter);
            }
        } catch (Throwable e) {
            log.error("error", e);
        }
    }


    public static String getRcdiId(String rcdiBefore){
        String rcdiBeforeId = null;
        JSONObject rootObject = JSON.parseObject(rcdiBefore);
        int code = rootObject.getIntValue("code");
        if (code == HttpStatus.OK.value()) {
            rcdiBeforeId = rootObject.getString("data");
        }
        return rcdiBeforeId;
    }
}
